package com.yunquan.ohana.dialog

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.view.LayoutInflater
import android.widget.TextView
import com.yunquan.ohana.R
import com.yunquan.ohana.base.ui.AppManager
import java.lang.ref.WeakReference

// 判断 Context 是否有效
fun Context.isContextValid(): Boolean {
    return this is Activity && !this.isFinishing && !this.isDestroyed
}

class LoadingDialog private constructor() {

    companion object {
        @Volatile
        private var instance: LoadingDialog? = null

        // 获取单例
        fun getInstance(): LoadingDialog {
            return instance ?: synchronized(this) {
                instance ?: LoadingDialog().also { instance = it }
            }
        }
    }

    private var dialog: Dialog? = null
    private val contextRef = WeakReference(AppManager.appManager.currentActivity())

    private fun create(context: Context) {
        dialog = Dialog(context, R.style.LoadingStyle).apply {
            val view = LayoutInflater.from(context).inflate(R.layout.dialog_loadding, null)
            setContentView(view)
            setCancelable(false) // 禁止手动取消
            setCanceledOnTouchOutside(false) // 点击外部不消失
            window?.setBackgroundDrawableResource(android.R.color.transparent)
        }
    }

    fun isShowing(): Boolean {
        return dialog?.isShowing ?: false
    }

    // 显示
    fun show(text: String? = null) {
        val context = AppManager.appManager.currentActivity()
        if (context != null) {
            if (!context.isContextValid()) return
            if (dialog == null || !dialog!!.isShowing) {
                create(context)
            }
            val message = text ?: context.getString(R.string.loading)
            dialog?.findViewById<TextView>(R.id.tvMessage)?.text = message
            dialog?.show()
        }
    }

    // 隐藏
    fun dismiss() {
        dialog?.takeIf { it.isShowing }?.dismiss()
        dialog = null
    }
}